package com.yeqian.service.impl;

import cn.hutool.core.date.DateTime;
import com.yeqian.pojo.Admin;
import com.yeqian.service.BaseService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author : yeqian
 * @Date : 2020/12/30 21:33
 * <p>
 * 权限服务接口
 */
@Service
public class SecurityUserService extends BaseService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin user = userMapper.getUserByUserName(username);

        if (user == null) {
            //说明用户名不存在
            return null;
        }
        user.setRecentLogin(new DateTime());
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new SimpleGrantedAuthority("root"));

        /**
         * 传递三个参数：
         * 用户名
         * 加密后的密码
         * 权限列表
         */
        //由于权限参数不能为空，所以这里先使用AuthorityUtils.commaSeparatedStringToAuthorityList方法模拟一个admin的权限，该方法可以将逗号分隔的字符串转换为权限集合。
//数据库中的密码是加密后的
            org.springframework.security.core.userdetails.User secrityUser
                = new org.springframework.security.core.userdetails.User(
                username, user.getPassword(), list
        );
        return secrityUser;
    }
}
